package cn.ug.operation.web.job;

import cn.ug.config.RedisGlobalLock;
import cn.ug.operation.mapper.entity.Lottery;
import cn.ug.operation.service.LotteryJoinMemberService;
import cn.ug.operation.service.LotteryService;
import cn.ug.util.UF;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class CalculateLotteryTimesTask {
    private Log log = LogFactory.getLog(CalculateLotteryTimesTask.class);
    @Autowired
    private LotteryService lotteryService;
    @Resource
    private RedisGlobalLock redisGlobalLock;
    @Autowired
    private LotteryJoinMemberService lotteryJoinMemberService;

    @Scheduled(cron = "0 0 1 * * ?")
   // @Scheduled(cron = "0 */1 * * * ?")
    public void calculateLotteryTimes() {
        List<Lottery> lotteries = lotteryService.queryUnderwayLottery();
        if (lotteries != null && lotteries.size() > 0) {
            String key = "CalculateLotteryTimesTask:calculateLotteryTimes:" + UF.getFormatDateTime("yyyy-MM-dd", UF.getDateTime());
            if(!redisGlobalLock.lock(key, 1, TimeUnit.DAYS)) {
                return;
            }
            for (Lottery lottery : lotteries) {
                if (lottery.getAccumulateNum() == 0) {
                    lotteryJoinMemberService.overlayTimes(lottery.getId(), lottery.getEverydayNum());
                } else if (lottery.getAccumulateNum() == 1) {
                    lotteryJoinMemberService.accumulateTimes(lottery.getId(), lottery.getEverydayNum());
                }
            }
        }
    }
}
